package cloud.xlh.digital_power_order.disruptor;

import cloud.xlh.digital_power_order.domian.order.OrderSaveDomain;
import cloud.xlh.digital_power_order.enums.OrderStatusEnum;
import cloud.xlh.digital_power_order.infrastructure.order.entity.OrderEntity;
import cloud.xlh.digital_power_order.service.order.adapter.OrderServiceAdapter;
import com.lmax.disruptor.RingBuffer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/8/23 22:55
 * @ Description:
 */
@Slf4j
@Component
@Service
public class DisruptorMqServiceImpl implements DisruptorMqService {

    @Resource(name = "orderEntityMessageModelRingBuffer")
    private RingBuffer<OrderEntity> orderEntityMessageModelRingBuffer;

    @Resource
    private OrderServiceAdapter orderServiceAdapter;

    @Override
    public void genOrderMessage(OrderSaveDomain orderSaveDomain) {
        log.info("record the message: {}",orderSaveDomain);
        //获取下一个Event槽的下标
        long sequence = orderEntityMessageModelRingBuffer.next();
        try {
            //给Event填充数据
            OrderEntity orderEntity = orderEntityMessageModelRingBuffer.get(sequence);
            orderEntity = orderServiceAdapter.convertOrderEntity(orderEntity , orderSaveDomain);
            orderEntity.setStatus(String.valueOf(OrderStatusEnum.INIT.getCode()));
            log.info("往消息队列中添加消息：{}", orderEntity);
        } catch (Exception e) {
            log.error("failed to add event to messageModelRingBuffer for : e = {},{}",e,e.getMessage());
        } finally {
            //发布Event，激活观察者去消费，将sequence传递给改消费者
            //注意最后的publish方法必须放在finally中以确保必须得到调用；如果某个请求的sequence未被提交将会堵塞后续的发布操作或者其他的producer
            orderEntityMessageModelRingBuffer.publish(sequence);
        }
    }
}
